﻿/**
 * ...
 * @author LuoDong
 * @email luo4521@online.net.tw
 */
package com.addcn.texas.model
{
	
	import com.addcn.fog.model.Model;
	
	import it.gotoandplay.smartfoxserver.SmartFoxClient;
	import it.gotoandplay.smartfoxserver.SFSEvent;
	
	import com.addcn.common.utils.Server;
	import com.addcn.common.data.ServerInfo;
	import com.addcn.common.data.Global;
	import com.addcn.common.data.UserInfoData;
	import com.addcn.texas.utils.MsgTable;
	
	public class StartupModel extends Model 
	{
		public static const CONNECTION_CUSS : String = "connectionCuss";
		public static const CONNECTION_LOST : String = "connectionLost";
		private var _server : SmartFoxClient = Server.getInstance();
		private var _info : UserInfoData;
		
		public function StartupModel() : void {
			_initialize();
			//connect();			
		}
		
		private function _initialize() : void 
		{
			var _data : ServerInfo = ServerInfo.getInstance(); 
			this._info = UserInfoData.getInstance();  
			//初始化Server,設置IP,端口等
			Server.initialize(_data.serverIp, _data.serverPort, _data.zone, _data.getExtList(),Global.getInstance().debug); 
			_server.addEventListener(SFSEvent.onConnection, _onConnectionHandler);
			_server.addEventListener(SFSEvent.onConnectionLost, _onConnectionLostHandler);			
			_server.addEventListener(SFSEvent.onLogin, _onLoginHandler);
			_server.addEventListener(SFSEvent.onRoomListUpdate, _onRoomListUpdateHandler);
		}
		
		public function connect() : void {
			if(!_server.isConnected){
				_server.connect(_server.ipAddress, _server.port);
			}
		}
		
		private function _onConnectionHandler(evt : SFSEvent) : void {
			if (evt.params.success) {
				if(_info.key){
					_server.login(_server.defaultZone, String(_info.id), String(_info.key));	
				}else{
					_server.login(_server.defaultZone, '1', "1");	
				}
			}else {
				sendNotification(CONNECTION_LOST, { code:"1002" } );
			}
		}
		
		//連接斷開
		private function _onConnectionLostHandler(evt : SFSEvent) : void {
			_server.isConnected = false;			
			sendNotification(CONNECTION_LOST, { code:"1001" } );
		}
		
		private function _onLoginHandler(evt : SFSEvent) : void {
		
			
		}
		
		//获取房间列表后调用
		private function _onRoomListUpdateHandler(evt : SFSEvent) : void {
			
		}
		
		
	}
	
}
